package com.hfzy.ihk.web.aliyuncall.biz;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dyvmsapi.model.v20170525.SmartCallRequest;
import com.aliyuncs.dyvmsapi.model.v20170525.SmartCallResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.hfzy.ihk.facade.aliyuncall.enums.AsrActionEnum;
import com.hfzy.ihk.facade.aliyuncall.vo.CallHistory;
import com.hfzy.ihk.web.aliyuncall.constant.AliyunAkInfo;
import com.hfzy.ihk.web.aliyuncall.constant.Constants;
import com.hfzy.ihk.web.aliyuncall.context.DisruptorInitBean;
import com.hfzy.ihk.web.aliyuncall.support.disruptor.DisruptorFactoryBean;
import com.hfzy.ihk.web.aliyuncall.support.disruptor.DisruptorSupport;
import com.hfzy.ihk.web.aliyuncall.support.disruptor.base.DisruptorEvent;
import com.hfzy.ihk.web.aliyuncall.vo.AsrCallOutParam;
import com.lmax.disruptor.RingBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 智能外呼呼出类
 */
@Lazy
@Component
public class AliyunAsrCallOutBiz extends DisruptorSupport<CallHistory,DisruptorEvent<CallHistory>> {


    @Resource
    private DisruptorInitBean disruptorInitBean;

    private static final Logger logger = LoggerFactory.getLogger(AliyunAsrCallOutBiz.class);

    /**
     * asr只能外呼呼出类
     * @param callOutParam
     * @return
     */
    public Map<String,String> AsrCallOutOpt(AsrCallOutParam callOutParam){

        Map<String,String> map = new HashMap<>();
        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliyunAkInfo.accessKeyId, AliyunAkInfo.accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", AliyunAkInfo.product, AliyunAkInfo.domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象-具体描述见控制台-文档部分内容
            SmartCallRequest request = new SmartCallRequest();

            request.setRecordFlag(true); //是否录音
            //必填-被叫显号,可在语音控制台中找到所购买的显号
            request.setCalledShowNumber(callOutParam.getShowNum());//"057128204523"
            //必填-被叫号码
            request.setCalledNumber(callOutParam.getMainCallPhone());//"13418035053"

            //可选-外部扩展字段
            request.setOutId(callOutParam.getExtend()); //扩展字段，这里为sessionId :"yourOutId"
            request.setSpeed(1);          //语速
            request.setVolume(2); // 	音量,-4到4之间，建议设为1
            request.setMuteTime(5000); //静音时长，单位ms，1000-20000之间，超过这个范围默认10000
            request.setPauseTime(600);  //停顿时长，单位ms，300-1200之间，超过这个范围默认800

            request.setActionCodeBreak(callOutParam.getActionCodeBreak()); //开场放音文件是否可打断，默认为true，打断
            //必填-语音文件ID
            if(callOutParam.getVoiceCode()!=null&&!callOutParam.getVoiceCode().equals("-1")){
                request.setVoiceCode(callOutParam.getVoiceCode());//"08a0e68a-9fbe-40b8-a8c5-335af67d89b3.wav"
            }else{
                request.setVoiceCode("$name$");
                Map<String,String> rmap = new HashMap<>();
                rmap.put("name",callOutParam.getVoiceCodeParam());
                request.setVoiceCodeParam(JSON.toJSONString(rmap));
            }


            request.setDynamicId(callOutParam.getExtend());
           // request.setAsrModelId("2070aca1eff146f9a7bc826f1c3d4d31");
            //hint 此处可能会抛出异常，注意catch
            SmartCallResponse smartCallResponse = acsClient.getAcsResponse(request);
            logger.info("aliyun call out result param->RequestId:{},Code:{},Message:{},CallId:{}",
                    smartCallResponse.getRequestId(),smartCallResponse.getCode(),smartCallResponse.getMessage(),smartCallResponse.getCallId());

            if (smartCallResponse.getCode() != null && smartCallResponse.getCode().equals("OK")) {
                map.put("result", Constants.SUCCESS);
                map.put("msg",smartCallResponse.getMessage());
                map.put("callOutCode",smartCallResponse.getCode());
                map.put("callId",smartCallResponse.getCallId());
                map.put("requestId",smartCallResponse.getRequestId());
                //请求成功
            }else{
                map.put("result", Constants.FAIL);
                map.put("callOutCode",smartCallResponse.getCode());
                map.put("msg",smartCallResponse.getMessage());
                map.put("callId",smartCallResponse.getCallId());
                map.put("requestId",smartCallResponse.getRequestId());
            }
        } catch (ClientException e) {
            e.printStackTrace();
            map.put("result", Constants.FAIL);
            map.put("msg","智能外呼失败，请重试");
        }

        return map;

    }


    /**
     * 进入智能外呼队列
     * @param data
     * @return
     */
    @Override
    protected RingBuffer<DisruptorEvent<CallHistory>> useRingBuffer(CallHistory data) {
        RingBuffer ringBuffer = null;
        String useType = "阿里云智能外呼呼出";
        ringBuffer = disruptorInitBean.getRingBufferAliyunAsrCallOut();
        checkRingBufferUse(ringBuffer,useType);
        return ringBuffer;
    }

    /**
     * 进队列呼出
     *
     * @param data
     * @throws Exception
     */
    public void todoCallOut(CallHistory data) throws Exception{
        putInRingBuffer(data);
    }

}
